import re
from typing import List

import pytest

import config
from utils.util_logger import logger


def replace_field(data: dict, api_session):
    """
        替换带有{{field}}或${field}的字段:
        session_request_class: UtilRequest类型
        data: 如：{'Authorization': 'Bearer {{access_token}}', 'Accept': '*/*'}

        api_session.TEST_CONTENT: dict类型,如{"access_token": "sdjsaoindskln.fdrfdsf.3wesea"}
    """
    logger.info(f"TEST_CONTENT: {api_session.content_class}")

    for k, v in data.items():
        # 判断是否是字符串，如果不是，则转换为字符串
        if not isinstance(v, str):
            v = str(v)
        # 判断{{field}}是否存在，则在TEST_CONTENT中查找替换
        if "{{" in v and "}}" in v:
            field_list = re.findall("{{(.*?)}}", v)
            if not field_list:
                continue
            else:
                for field in field_list:
                    get_replace_value = api_session.content_class.get("field", None)         # "sdjsaoindskln.fdrfdsf.3wesea"
                    if not replace_field:
                        logger.error(f"{field} not in {api_session.content_class}!")
                        pytest.fail(reason=f"{field} not in {api_session.content_class}!")
                    else:       
                        # 将字符串转换为dict                                       # 'Bearer {{access_token}}'
                        k_str = re.sub(f"{{field}}", get_replace_value, str(data[k]))
                        data[k] = dict(k_str)
                        logger.info(f"{k: data[k]}")
        elif "${" in v and "}" in v:
            # 判断${field}是否存在，存在则在config中查找替换
            field_list: List[str] = re.findall(r"\$\{(.*?)\}", v)
            if not field_list:
                continue
            else:
                for field in field_list:
                    try:
                        get_replace_value = getattr(config, field.upper())
                        k_str = re.sub(r"\$\{(.*?)\}", get_replace_value, str(data[k]))
                        logger.info(f"k_str: {k_str}")
                        data[k] = dict(k_str)
                        logger.info(f"{k: data[k_str]}")
                    except Exception as e:
                        logger.error(f"{field.upper()} not in config.py")
    return data
